/**
 * 
 */

package proxy;


import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.COOKIE;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.SET_COOKIE;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.SET_COOKIE2;

import java.io.IOException;
import java.net.SocketAddress;

import misc.CLoggerFactory;

import org.apache.log4j.Logger;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;

import proxy.ProxyServer.EServerMode;


public class HostResponseHandler extends SimpleChannelUpstreamHandler {

	HttpResponse ResponseFromHost;
	HttpRequest  RequestFromHost;
	private Logger log;
	private Logger HostResponseLog;
	
    public HostResponseHandler(HttpRequest request) {
		this.RequestFromHost=request;
		
		try {
	    	this.log=CLoggerFactory.getFileLogger("HostResponseHandler", "HostResponseHandler.log") ;
			this.HostResponseLog = CLoggerFactory.getFileLogger("HostResponses", "HostResponses.log") ;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	@Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    	this.ResponseFromHost = (HttpResponse) e.getMessage();
    	SocketAddress LocalAddress =ctx.getChannel().getLocalAddress();
    	
    	HostResponseLog.info("Response From host address: " +
					 LocalAddress + " ********* \n" +
					 ResponseFromHost + "\n");
    	
    	//if the server is running in Anonymous Mode - remove all related headers
    	if (ProxyServer.serverMode == EServerMode.EAnonymousMode ){
	    	ResponseFromHost.removeHeader(COOKIE);
	    	ResponseFromHost.removeHeader("P3P");
	    	ResponseFromHost.removeHeader(SET_COOKIE);
	    	ResponseFromHost.removeHeader(SET_COOKIE2);
    	}
    	
    	e.getChannel().close();
    }
    
    public HttpResponse getResponseFromHost(){
    	return ResponseFromHost;
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
            throws Exception {
    	log.debug("exception Caught in HostResponseHandler " + e.getCause());
        e.getCause().printStackTrace();
        e.getChannel().close();
    }
    
    /**
     * this method overrides the default method by sending
     * straight after the channel has Connected the request 
     * that came from the client
     */
    @Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    	e.getChannel().write(this.RequestFromHost);
    }	
	
}
